package jdbc;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

/**
 * 登录验证与SQL注入攻击
 * 用户输入用户名、密码,数据库校验
 * 正确:登录成功,欢迎你:昵称
 * 错误:用户名或密码错误
 * SELECT id,username,password,nickname FROM userinfo
 * WHERE username='?' AND password='?'
 */
public class JDBCDemo7 {
    public static void main(String[] args) {
        try (Connection connection = DBUtil.getConnection();){
            // 接收用户输入
            Scanner scanner = new Scanner(System.in);
            System.out.println("登录功能");
            System.out.println("请输入用户名:");
            String username = scanner.nextLine();
            System.out.println("请输入密码:");
            String password = scanner.nextLine();
            // 执行SQL语句
            Statement statement = connection.createStatement();
            String sql = "SELECT id,username,password,nickname " +
                    "FROM userinfo " +
                    "WHERE username='"+username+"' " +
                    "AND password='"+password+"'";
            ResultSet resultSet = statement.executeQuery(sql);

            // 判断结果
            if (resultSet.next()){
                String nickname = resultSet.getString("nickname");
                System.out.println("登录成功,欢迎你:" + nickname);
            }else{
                System.out.println("用户名或密码错误");
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
    }
}
